/* eslint-disable react/no-multi-comp */
import React, { PureComponent } from 'react';
import { Row, Col, Card, Button } from 'antd';

class CustomTextInput extends PureComponent {
  focusTextInput = () => {
    // 1. 直接使用原生 API 使 text 输入框获得焦点
    this.textInput.focus();
  };

  render() {
    // 使用 `ref` 的回调将 text 输入框的 DOM 节点存储到 React
    // 实例上（比如 this.textInput）
    return (
      <div>
        <input type="text" ref={(input) => { this.textInput = input; }} />
        <input type="button" value="Focus the text input " onClick={this.focusTextInput} />
      </div>
    );
  }
}

// 函数组件
// 父组件传递函数 inputRef 给子组件，子组件把 inputRef 函数和 ref 链接
function ChildInput(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>
  );
}

// 受控组件
class Reservation extends PureComponent {
  state = {
    isGoing: true,
    numberOfGuests: 2,
  };

  handleInputChange = (e) => {
    const { target } = e;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const { name } = target;

    this.setState({ [name]: value });
  };

  render() {
    return (
      <form>
        <label htmlFor="Is going">
          <input type="checkbox" name="isGoing" checked={this.state.isGoing} onChange={this.handleInputChange} />
        </label>
        <label htmlFor="Number of guests">
          <input type="number" name="numberOfGuests" value={this.state.numberOfGuests} onChange={this.handleInputChange} />
        </label>
      </form>
    );
  }
}

// 2. 类组件的 ref
export default class Demo6Componnet extends PureComponent {
  // 组件初始化时，聚焦 input
  componentDidMount() {
    // 调用子组件上的方法
    this.textInput.focusTextInput();
  }
  focusInput = () => {
    this.inputElement.focus();
    this.inputElement.value = '我被聚焦了';
  };

  render() {
    return (
      <div>
        <h4>ref的使用</h4>
        <Card title="ref指向底层的Dom">
          <CustomTextInput ref={(input) => { this.textInput = input; }} />
        </Card>
        <Card title="父组件利用 props 传递函数获取 ref">
          <ChildInput inputRef={(el) => { this.inputElement = el; }} />
          <Button type="primay" onClick={this.focusInput}>聚焦input</Button>
        </Card>
        <h4>受控组件和非受控组件</h4>
        <Card title="受控组件">
          <h4>受控组件</h4>
          <Reservation />
        </Card>
      </div>
    );
  }
}
